package com.wing.setting.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.setting.model.entity.SysSetting;
import com.wing.setting.model.entity.SysSettingAdvert;
import com.wing.setting.model.request.SysSettingForm;
import com.wing.setting.model.response.SysSettingVO;
import com.wing.setting.service.SysSettingAdvertService;
import com.wing.setting.service.SysSettingService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-刀具柜系统设置管理", tags = "#/setting/sysSetting")
@RestController("adminSettingController")
@RequestMapping("setting/admin/sysSetting")
@Slf4j
@RequiredArgsConstructor
public class SettingController {

    private final SysSettingService sysSettingService;

    private final SysSettingAdvertService advertService;


    @ApiOperation(value = "查询所有刀具柜系统设置", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SysSetting> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
    ){

        Page<SysSetting> pg = new Page<>(page, limit);
        QueryWrapper<SysSetting> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索

        IPage<SysSetting> list = sysSettingService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加刀具柜系统设置", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(SysSettingForm.Add.class) SysSettingForm sysSettingForm) {
        try {
            if (sysSettingService.add(sysSettingForm) > 0) {
                return JsonResult.success("添加成功");
            }
        } catch (Exception e) {
            log.error("刀具柜系统设置原因：",e);
            return JsonResult.error(555,"异常原因："+e.getMessage());
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改刀具柜系统设置", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(SysSettingForm.Update.class) SysSettingForm sysSettingForm) {
        SysSetting sysSetting = sysSettingService.getById(sysSettingForm.getId());
        if(sysSetting == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SysSetting.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(sysSettingForm, sysSetting, copyOptions);
        if (sysSettingService.updateById(sysSetting)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除刀具柜系统设置", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysSettingId", value = "刀具柜系统设置id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long sysSettingId) {
        if (sysSettingService.removeById(sysSettingId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    /**
     * 企业端/柜子面板down  广告列表
     */
    @GetMapping("/getSettingCabInfo")
    public JsonResult<SysSettingVO> getSettingCabInfo(){
        try {
            return JsonResult.success(sysSettingService.getSettingCabInfo());
        }catch (Exception e){
            log.error("getSettingCabInfo fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    /**
     * 根据id修改是否启用
     */
    @PutMapping("/upIsDelete")
    public JsonResult upIsDelete(@RequestParam("id") Long id,@RequestParam("isDeleted") Integer isDeleted){

        if (advertService.upIsDelete(id,isDeleted)){
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");

    }

    /**
     * 根据id关联查询
     */
    @GetMapping("/getSettingById")
    public JsonResult getSettingById(@RequestParam("id")Long id){
        SysSettingAdvert advert = advertService.getById(id);
        return JsonResult.success(advert);
    }

    /**
     * 广告信息关联查询
     */
    @GetMapping("/getSettingListByParam")
    public JsonResult getSettingListByParam(String enterpriseCode,Long advertId){
        Map<String, Object> params = new HashMap<>();
        params.put("enterpriseCode",enterpriseCode);
        params.put("advertId",advertId);

        List<SysSettingVO> list = sysSettingService.getSettingListByParam(params);
        return JsonResult.success(list);
    }

    /**
     * 修改详情
     */
    @PostMapping("/upDate")
    public JsonResult upDate(@RequestBody SysSettingVO sysSettingVO){

        if (!sysSettingService.upSetting(sysSettingVO)){
            return JsonResult.fail("修改失败");
        }
        return JsonResult.success("修改成功");
    }

}
